package main

import (
	"common/rtpengine"
	"common/rtpengine/media"
	"common/rtpengine/rtp/codecs"
	"flag"
	"fmt"
	"io/ioutil"
	"net"
	"os"
	"strings"
	"time"
)

var defaultConcurrent = 200

func main() {
	buf, err := ioutil.ReadFile("media/dudud_29s.wav")
	if err != nil {
		fmt.Printf("cannot open input file:%v\n. ", err)
		return
	}

	// current := flag.Int("t", defaultConcurrent, "Total Concurrent")
	flag.Parse()

	stop := make(chan interface{})

	// The remote listen the local message： listen and print message
	if false {
		remoteIp, _ := net.ResolveIPAddr("ip", "127.0.0.1")
		listen(stop, remoteIp, 6220)
	} else {
		testTrackLocalReceive(stop) // 127.0.0.1:6220
	}

	trackLocal := rtpengine.NewTrackLocal("testTrack1234", "127.0.0.1:6440")
	binds := rtpengine.SenderBinding{RightAddr: "127.0.0.1:6220", PayloadType: 101, Payloader: &codecs.G711Payloader{}, Options: rtpengine.SenderBindingOptions{Mtu: codecs.PCMAPayLoadLength}}
	trackLocal.Bind(binds)
	trackLocal.SetSamples(8000)
	if err := trackLocal.StartSession(rtpengine.Config{}); err != nil {
		fmt.Printf("StartSession failed:%v\n. ", err)
		return
	}

	startTime := time.Now()
	dataSamples := media.Sample{Data: buf, PrevDroppedPackets: 0}
	if err := trackLocal.WriteSample(dataSamples); err != nil {
		fmt.Printf("WriteSample failed:%v\n. ", err)
		return
	}

	// The local start send rtp to remote
	// tpLocal, _ := rtpengine.NewTransportUDP("127.0.0.1", 52200)
	//rtpSession := RTP2.NewSession(tpLocal, tpLocal)
	//rtpSession.SetRemote(RTP2.Address{IPAddr: remoteIp, DataPort: 6220, CtrlPort: 6221})
	//
	//g711Code := RTP2.NewRTPPCMACodec(8, 8000)
	//track, _ := RTP2.NewTrack(8, 1, "1", "test", g711Code)
	//
	//rtpSender, _ := RTP2.NewRTPSender(track, rtpSession)
	//header := &RTP2.Header{PayloadType: 8}
	//
	//var futures []RTP2.Future
	//for i := 0; i < *current; i++ {
	//	future := rtpSender.SendRTP(header, buf)
	//	futures = append(futures, future)
	//}
	//
	//var bytes int
	//if len(futures) != 0 {
	//	for index, future := range futures {
	//		asyncResult := future.Get()
	//		if asyncResult.Error() != nil {
	//			log.Printf("The %dth Send Rtp fail, the error is %s", index, asyncResult.Error().Error())
	//			continue
	//		}
	//		bytes += asyncResult.Data().(int)
	//	}
	//}
	fmt.Printf("Ending send rtp, concurrent is 1, totalBytes is %d, duration is %fs\n", len(buf), time.Since(startTime).Seconds())

	<-stop
}

func listen(stop chan interface{}, remote *net.IPAddr, port int) {
	remoteAddr, _ := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", remote, port))
	remoteConn, err := net.ListenUDP("udp", remoteAddr)
	if err != nil {
		fmt.Printf("Listen the remote addr fail:%v... \n", err)
		os.Exit(-1)
	}
	_ = remoteConn.SetReadBuffer(5242880)
	go receiveLocalMessage(stop, remoteConn)
}

func receiveLocalMessage(stop chan interface{}, conn *net.UDPConn) {
	defer close(stop)
	defer conn.Close()

	var currentBytes int
	var temp [1500]byte
	for {
		// 无限循环.
		// 默认每次读到1200个字节.
		receiveBytes, _, err := conn.ReadFromUDP(temp[0:])
		if err != nil {
			fmt.Printf("Receive the message fail, the error is %s\n", err.Error())
			return
		}
		currentBytes += receiveBytes
		fmt.Printf("Receive the message success, the current lenth is %d\n", currentBytes)
	}
}

func testTrackLocalReceive(stop chan interface{}) {
	// 用track进行接收.
	trackLocal := rtpengine.NewTrackLocal("testTrack4321", "127.0.0.1:6220")
	binds := rtpengine.SenderBinding{RightAddr: "127.0.0.1:6440", PayloadType: 101, Payloader: &codecs.G711Payloader{}}
	trackLocal.Bind(binds)
	trackLocal.SetSamples(8000)
	if err := trackLocal.StartSession(rtpengine.Config{}); err != nil {
		fmt.Printf("StartSession failed:%v\n. ", err)
		return
	}

	go receiveMessageFromTrack(stop, trackLocal)
}

func receiveMessageFromTrack(stop chan interface{}, trackLocal *rtpengine.TrackLocal) {
	defer close(stop)
	r, ssrc, err := trackLocal.AcceptStream()
	if err != nil {
		fmt.Printf("AcceptStream failed:%v\n. ", err)
		return
	}
	fmt.Printf("AcceptStream successed, ssrc is:%d\n. ", ssrc)

	var currentBytes int
	var temp [1500]byte
	// start to receive.
	for {
		// 无限循环.
		// 默认每次读到1200个字节.
		_ = r.SetReadDeadline(time.Now().Add(time.Second))
		receiveBytes, err := r.Read(temp[0:])
		if strings.Contains(err.Error(), "timeout") {
			// normal read done
			return
		} else if err != nil {
			// If time.Second passed and no more data arrives, just exit.
			fmt.Printf("Receive the message fail, the error is %s", err.Error())
			return
		}
		currentBytes += receiveBytes
		fmt.Printf("Receive the message "+
			""+
			", the current lenth is %d\n", currentBytes)
	}
}

// 测试rtpsender..
func testRTPSender() {

}
